import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 30. 串联所有单词的子串
 * https://leetcode.cn/problems/substring-with-concatenation-of-all-words/description/
 */
class Solution3 {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> ret = new LinkedList<>();

        Map<String, Integer> hash1 = new HashMap<>();
        for(String x : words) hash1.put(x, hash1.getOrDefault(x, 0) + 1);

        int len = words[0].length(), m = words.length;
        for(int i = 0; i < len; i++) {
            Map<String, Integer> hash2 = new HashMap<>(); // 保存窗口内的所有字符串
            for(int left = i, right = i, count = 0; right + len <= s.length(); right += len) {
                // 1、进窗口
                String in = s.substring(right, right + len);
                hash2.put(in, hash2.getOrDefault(in, 0) + 1);
                // 维护有效字符串的个数
                if(hash2.get(in) <= hash1.getOrDefault(in, 0)) count++;
                // 2、判断
                if(right - left + 1 > len * m) {
                    String out = s.substring(left, left + len);
                    // 维护有效字符串的个数
                    if(hash2.get(out) <= hash1.getOrDefault(out, 0)) count--;
                    // 出窗口
                    hash2.put(out, hash2.get(out) - 1);
                    left += len;
                }
                // 3、更新结果
                if(count == m) ret.add(left);
            }
        }
        return ret;
    }
}